package com.sanss.log_plat.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sanss.log_plat.utils.SendEmail;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class CJ01ErrorListener {

    private RestTemplate restTemplate = new RestTemplate();

//    @Scheduled(cron = "0 */5 * * * ?")
    public void errorSendToEmail() {
        String reqString =
                "{\n" +
                        "    \"query\": { \"match\": {\n" +
                        "        \"message\": \"ERROR\"\n" +
                        "    } },\n" +
                        "    \"_source\": [\"message\"]\n" +
                        "}";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(reqString,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://172.16.53.132:9200/catalina.out-cj01-2017.11.20/_search?pretty", HttpMethod.POST,
                entity, String.class);
//        System.out.println(responseEntity.getBody());
        String result = responseEntity.getBody();
        System.out.println("搜索成功");
        JSONObject resJSON = JSONObject.parseObject(result);
        JSONObject hitsObject = resJSON.getJSONObject("hits");
        Integer total = hitsObject.getInteger("total");
        if(total > 0){
            JSONArray hitArray = hitsObject.getJSONArray("hits");
            System.out.println(hitArray);
//            SendEmail.send();
        }


    }
}
